<template>
	<div class="app-container">
		<div id="N-course-box" class="NXB-cbox" :style="showContent?'right:320px':'right:0px'">
			<article class="NXB-pc-wrap">
				<div>
					<div class="N-pr-loading"></div>
					<a href="javascript:;" class="cl-back" @click="routerHistory"></a>
					<div class="N-l-title">
						<section class="N-l-t-box">
							<h3 class="N-l-t-title">
								<span class="N-l-tt-name">{{courseInfo.name}}</span>
								<span class="N-l-tt-x" id="kpointName">{{playObj.name}}</span>
							</h3>
						</section>
					</div>
					
					<div class="pl-flash-box pl-audio-box" style="overflow: hidden;" id="videoBox">
						<div class="back-contain" @click="startPlayOrPause">
							<img src="" alt="" />
						</div>
						<div class="audio-contain">
							<audio ref="audio" 
							    @pause="onPause"
							    @play="onPlay"
							    @timeupdate="onTimeupdate" 
							    @loadedmetadata="onLoadedmetadata"
							    :src="playObj.fileurl"
							>
							</audio>
							
							<el-slider v-model="sliderTime" :format-tooltip="formatProcessToolTip" @change="changeCurrentTime" class="slider" width="98%"></el-slider>
							<div>
								<el-button  class="ml15" type="text" @click="startPlayOrPause">{{audio.playing | transPlayPause}}</el-button>
						    	<span class="c-fff ">{{ audio.currentTime | formatSecond}}</span>
								<span class="c-fff">/</span>
								<span class="c-fff ">{{ audio.maxTime | formatSecond}}</span>	
							</div>	
							
							
						</div>
					</div>
				</div>
				<!-- left area element -->
			</article>
		</div>
		<div id="N-toolBar-box" class="NXB-cTool open"  :style="showContent?'width:320px':'width:0px'">
			<div class="nct-bo">
				<section class="n-ctInfo">
					<div class="n-c-attr-box">
						<h3 class="hLh30 txtOf">
							<a class="c-fff fsize20" title="" href="https://t.nxb100.com/front/course/info?id=527">{{courseInfo.name}}</a>
						</h3>
					</div>
					<div class="hLh30 txtOf">
						<aside class="fl" title="学习人数"><em class="icon12 person-icon"></em><small class="fsize12 vam c-master2">{{courseInfo.lessonNum}}</small></aside>
						<aside class="fl ml30" title="评论数"><em class="icon16 c-review-num"></em><small class="fsize12 vam c-master2">{{assessList.length}}</small></aside>
						<a href="javascript:;" title="考试" class="fr exam-enter-btn" @click="joinExam" v-if="courseInfo.paperId">考试</a>
					</div>

				</section>
				<div class="N-hiderightbtn">
					<div class="n-ctTab" id="MN-hideRightBtn">
						<a href="javascript:void(0)" lang="n-ct-cont-menu" :class="showType == 'chapt'?'current':''" title="章节" @click="changeShowType('chapt')">章节</a>
						<!--						<a href="javascript:void(0)" lang="n-ct-cont-notice" :class="showType == 'noteBook'?'current':''" title="笔记" @click="showType = 'noteBook'">笔记</a>-->
						<a href="javascript:void(0)" lang="n-ct-cont-answer" :class="showType == 'comment'?'current':''" title="评论" @click="changeShowType('comment')">评论</a>
					</div>
				</div>
				<section class="n-ctCont-box">
					<article class="n-ct-cont-menu" v-show="showType =='chapt'">
						<div class="n-ct-of">
							<div v-for="item in courseInfo.courseChapters">
								<div class="cou-info-menu">
									<div class="chapter-name txtOf" style="background: none;"><span class="">{{item.name}}</span></div>
								</div>
								

								<div class="chap-seclist pr" v-for="childItem in item.children">
									<ul>
										<li class="kpoint_list kpoint_1846 c-chapter-ongoing" :class="childItem.id == playObj.id?'current':''" @click="changeSection(childItem)">
											<div class="c-p-wrap">
												<a class="play-icon-box c-p-title txtOf" :title="childItem.name" href="javascript:void(0)">
													<em class="icon16 vam"></em>
													<span class="ml5 vam">{{childItem.name}}</span>
													<small class="vam fsize12 c-666 f-fM">（{{childItem.minutes}}分钟）</small>
													<!--<span class="c-666 ml5 f-fM vam c-learn-sec"><span class="c-master kpoint_progress_1846">6%</span></span>-->
												</a>
											</div>
										</li>
									</ul>
								</div>
							</div>
						</div>
					</article>
					<!-- /目录 区域 结束 -->
					<!--<article class="n-ct-cont-notice" v-show="showType =='noteBook'">
						<div class="mt10 pl15 pr15">
							<div class="of">
								<section class="n-reply-wrap">
									<textarea id="notesContextId" placeholder="此刻记录你的心得..." style="height: 300px;" class="f-fM n-note-reply" name=""></textarea>
									<p class="of mt5 tar pl10">
										<a class="lh-reply-btn ml15" title="保 存" href="javascript:void(0)" onclick="addNote()">保存</a>
									</p>
								</section>
							</div>
						</div>
					</article>-->
					<!-- /笔记 区域 结束 -->

					<article class="n-ct-cont-answer" v-show="showType =='comment'">
						<div class="mt10 pl15 pr10">
							<div class="of">
								<section class="n-reply-wrap">
									<fieldset>
										<textarea id="problemContextTextareaId" v-model="commentInfo" maxlength="255" placeholder="写下你的问题，平台讲师或热心员工们会帮你解答..." class="f-fM" name=""></textarea>
									</fieldset>
									<p class="of mt5 tar pl5">

										<a class="lh-reply-btn ml15" title="提 交" href="javascript:void(0)" @click="addReview">提 交</a>
									</p>
								</section>
							</div>
							<div class="mt10 hLh30 n-ctcn-tit"><span class="fsize14 c-333">全部评论({{assessList.length}})</span></div>
						</div>
						<div>
							<div class="n-ct-of">
								<section class="n-ct-cont-notice-list">
									<section class="review-box question-list">
										<ul>
											<li class="pr" lang="217" v-for="item in assessList">
												<aside class="noter-pic">
													<img width="40" height="40" class="picImg" :src="item.user.avatar">
												</aside>
												<div class="of">
													<span class="fl">
														<font class="fsize14 c-999">{{item.user.nickname}}</font>
													</span>
													<span class="fr c-666 fsize12">{{item.createtime}}</span>
												</div>
												<div class="noter-txt mt5">
													<p>{{item.info}}</p>
												</div>
												<div class="tar">
													<a href="javascript:void(0)" class="c-666 fsize14" title="回复" @click="showReply = item.id"><em class="icon18 c-reply"></em></a>
												</div>
												<div class="n-reply mt5" id="reply217" v-show="showReply == item.id">
													<section class="n-reply-wrap">
														<fieldset><textarea class="" maxlength="255" name="" id="reProblemInfo217" v-model="replyInfo"></textarea></fieldset>
														<p class="of mt5 tar pl5 pr5">

															<a class="lh-reply-btn ml15" title="回复" href="javascript:void(0)" @click="reply(item.id)">回复</a>
														</p>
													</section>
													<div class="mt10 reply-list">
														<section class="review-box mt15">
															<ul>
																<li class="pr" v-for="childItem in item.courseAssessList">
																	<aside class="noter-pic">
																		<img width="40" height="40" :src="childItem.user.avatar" class="picImg">
																	</aside>
																	<div class="of"><span class="fl"><font class="fsize16 c-blue1">{{childItem.user.nickname}}</font></span>
																		<span class="fr c-666 fsize12"><font>{{childItem.createtime}}</font></span>
																	</div>
																	<div class="noter-txt mt5">
																		<p>{{childItem.info}}</p>
																	</div>
																</li>

															</ul>
														</section>
													</div>
												</div>
											</li>

										</ul>
									</section>
								</section>
							</div>
						</div>
					</article>
					<!-- /答疑 区域 结束 -->

					< </section>
			</div>
		</div>
	</div>
</template>

<script>
	
	// 将整数转换成 时：分：秒的格式
	function realFormatSecond(second) {
	  var secondType = typeof second
	
	  if (secondType === 'number' || secondType === 'string') {
	    second = parseInt(second)
	
	    var hours = Math.floor(second / 3600)
	    second = second - hours * 3600
	    var mimute = Math.floor(second / 60)
	    second = second - mimute * 60
	
	    return  ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2)
	  } else {
	    return '00:00'
	  }
	}
	import { Notification } from 'element-ui';
	import { domainUrl } from '@/utils/index'
	import { getCourseInfo, getAssessList, insertAssess, insertHistory, updateHistory ,updateRecord} from '@/api/course'
	export default {
		data() {
			return {
				audioDomain:"http://file.quality-in.com",
				courseInfo: {},
				assessList: [],
				showType: "chapt",
				showContent:true,
				showReply: "",
				commentInfo: "",
				replyInfo: "",
				playId: 0, //当前播放章节id
				playObj: {
					fileurl:""
				},
				historyId: 0,
				historyStr: null, //setIn 动画
				taskId:0,//任务id 用于任务课程
				audio: {
			        // 该字段是音频是否处于播放状态的属性
			        playing: false,
			        // 音频当前播放时长
			        currentTime: 0,
			        // 音频最大播放时长
			        maxTime: 0
			      },
			      sliderTime:0
			}
		},
		created() {
			let query = this.$route.query;
			let userInfo = this.getUserInfo();
			this.playId = query.playId;
			this.userInfo = userInfo;
			this.domain = domainUrl();
			this.getCourseInfo(query.id, userInfo.id);
			this.getAssessList({
				courseId: query.id,
				currentPage: 1
			});
			if(query.taskId){
				this.taskId = query.taskId;
			};
			
		},
		
		methods: {
			updateRecord(data){
				updateRecord(data).then((res)=>{
					
				})
			},
			getUserInfo() {
				return this.$store.getters.getStorageInfo;
			},
			getPlayingSection(id) { //查找当前对象
				let playObj = {};
				let courseChapters = this.courseInfo.courseChapters;
				if(id != 0) {
					courseChapters.forEach((item) => {
						item.children.forEach((childItem) => {
							if(id == childItem.id) {
								playObj = childItem;
							}
						})
					})
				} else {
					playObj = courseChapters[0].children[0];
				};
				playObj.fileurl = this.audioDomain+''+playObj.fileurl;
				this.playObj = playObj;
				this.playVoice(this.playObj);

			},
			getAssessList(page) {
				getAssessList(page).then((res) => {
					let data = res.entity.data;
					data.forEach((item) => {
						if(!item.user.avatar) {
							item.user.avatar = '';
						} else {
							item.user.avatar = domainUrl() + item.user.avatar;
						}
						item.courseAssessList.forEach((childItem) => {
							if(!childItem.user.avatar) {
								childItem.user.avatar = '';
							} else {
								childItem.user.avatar = domainUrl() + childItem.user.avatar;
							}
						})
					});
					this.assessList = data;
				})
			},
			getCourseInfo(id, userId) {
				getCourseInfo(id, userId).then((res) => {
					let data = res.entity;
					this.courseInfo = data.course;
					this.courseAuth = data.courseAuth;
					this.getPlayingSection(this.playId);
				})
			},
			insertAssess(page) { //提交评论
				insertAssess(page).then((res) => {
					this.getAssessList({
						courseId: this.courseInfo.id,
						currentPage: 1
					});
					this.commentInfo = "";
					this.replyInfo = "";
					
				});
			},
			playVoice(vid) {
				
				let data = {
					userId: this.userInfo.id,
					courseId: this.courseInfo.id,
					courseName: this.courseInfo.name,
					chapterId: this.playObj.id,
					chapterName: this.playObj.name,
					lookfrom: 'WEB'
				};
				insertHistory(data).then((res) => {
					this.historyId = res.entity.id;
					this.play();
				});
			},
			updateHistory() {
				let that = this;
				this.historyStr = setInterval(function() {
					updateHistory(that.historyId).then((res) => {

					});
				}, 60000);

			},
			clearTime(){//清除定时器
				clearInterval(this.historyStr);
				this.historyStr = null;
			},
			addReview() {
				let data = {
					courseId: this.courseInfo.id,
					chapterId: 0,
					info: this.commentInfo,
					userId: this.getUserInfo().id
				};
				if(this.commentInfo !== "") {
					data.info = this.commentInfo;
					this.insertAssess(data);
				} else {
					Notification.warning({
				 		title: '提示',
 						message: '请输入评论内容',
 						position: 'top-left'
				 	});
				};
			},
			reply(id) {
				let data = {
					courseId: this.courseInfo.id,
					chapterId: 0,
					info: this.replyInfo,
					userId: this.getUserInfo().id
				};
				data["replyId"] = id;
				if(this.replyInfo !== "") {
					data.info = this.replyInfo;
					this.insertAssess(data);
				} else {
					Notification.warning({
				 		title: '提示',
 						message: '请输入评论内容',
 						position: 'top-left'
				 	});
				};
			},
			changeSection(obj) {
				obj.fileurl = this.audioDomain+''+obj.fileurl;
				this.playObj = obj;
				this.playVoice(obj.fileurl)
			},
			routerHistory() { //返回
				this.$router.go(-1)
			},
			joinExam() {
				this.$router.push({
					path: '/exam',
					query: {
						courseId: this.courseInfo.id,
						paperId: this.courseInfo.paperId,
						type: 'COURSE',
						name:this.courseInfo.name
					}
				})
			},
			changeShowType(val){
				if(val == this.showType){
					this.changeShowContent();
				}else{
					this.showType = val;	
					this.showContent = true;
				};
				
			},
			changeShowContent(){
				this.showContent?this.showContent = false:this.showContent = true;
			},
			  // 控制音频的播放与暂停
		    startPlayOrPause () {
		      return this.audio.playing ? this.pause() : this.play()
		    },
		    // 播放音频
		    play () {
		      this.$refs.audio.play()
		      this.clearTime();
			  this.updateHistory();
		    },
		    // 暂停音频
		    pause () {
		      this.$refs.audio.pause()
		      this.clearTime();
		    },
		    // 当音频播放
		    onPlay () {
		      this.audio.playing = true
		    },
		    // 当音频暂停
		    onPause () {
		      this.audio.playing = false
		    },
		    // 当加载语音流元数据完成后，会触发该事件的回调函数
		    // 语音元数据主要是语音的长度之类的数据
		    onLoadedmetadata(res) {
		      this.audio.maxTime = parseInt(res.target.duration);
		      
		    },
		    // 拖动进度条，改变当前时间，index是进度条改变时的回调函数的参数0-100之间，需要换算成实际时间
			changeCurrentTime(index) {
			  this.$refs.audio.currentTime = parseInt(index / 100 * this.audio.maxTime);
			  this.play();
			},
			// 当音频当前时间改变后，进度条也要改变
			onTimeupdate(res) {
			  this.audio.currentTime = res.target.currentTime
			  this.sliderTime = Number(this.audio.currentTime / this.audio.maxTime * 100);
			},
			
			// 进度条格式化toolTip
			formatProcessToolTip(index = 0) {
			  index = parseInt(this.audio.maxTime / 100 * index)
			  return '时间: ' + realFormatSecond(index)
			},

		},
		filters: {
		    // 使用组件过滤器来动态改变按钮的显示
		    transPlayPause(value) {
		      return value ? '暂停' : '播放'
		    },
		    // 将整数转化成时分秒
		    formatSecond(second = 0) {
		      return realFormatSecond(second)
		    }
		},
		beforeRouteLeave(to, from, next) {

			this.clearTime();
			next();
		}
	}
</script>

<style scoped>
	@import '../../assets/style/play-learn-nxb.css'
</style>